package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
	
	@Autowired
	private ShoppingCartMapper shoppingCartMapper;
	@Autowired
	private DishService dishService;
	@Autowired
	private SetmealService setmealService;
	
	/**
	 * 添加购物车
	 *
	 * @param shoppingCartDTO
	 */
	@Override
	public void addCart(ShoppingCartDTO shoppingCartDTO) {
		ShoppingCart cart =
			ShoppingCart.builder().userId(BaseContext.getCurrentId()).dishId(shoppingCartDTO.getDishId()).setmealId(shoppingCartDTO.getSetmealId()).dishFlavor(shoppingCartDTO.getDishFlavor()).build();
		List<ShoppingCart> shoppingCartList = shoppingCartMapper.getCart(cart);
		// 商品存在
		if (shoppingCartList != null && !shoppingCartList.isEmpty()) {
			shoppingCartList.get(0).setNumber(shoppingCartList.get(0).getNumber() + 1);
			shoppingCartMapper.putCartNumber(shoppingCartList.get(0));
		} else {
			// 商品不存在
			if (shoppingCartDTO.getDishId() != null) {
				DishVO dish = dishService.getDishId(shoppingCartDTO.getDishId());
				cart.setName(dish.getName());
				cart.setImage(dish.getImage());
				cart.setAmount(dish.getPrice());
			} else {
				SetmealVO setmealVO = setmealService.getSetmealId(shoppingCartDTO.getSetmealId());
				cart.setName(setmealVO.getName());
				cart.setImage(setmealVO.getImage());
				cart.setAmount(setmealVO.getPrice());
			}
			cart.setNumber(1);
			cart.setCreateTime(LocalDateTime.now());
			shoppingCartMapper.addCart(cart);
		}
	}
	
	/**
	 * 查看购物车
	 *
	 * @return
	 */
	@Override
	public List<ShoppingCart> getCart() {
		return shoppingCartMapper.getCart(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
	}
	
	/**
	 * 删除购物车
	 */
	@Override
	public void deleteCart() {
		shoppingCartMapper.deleteCart(BaseContext.getCurrentId());
	}
	
	/**
	 * 删除商品数量
	 */
	@Override
	public void putCart(ShoppingCartDTO shoppingCartDTO) {
		ShoppingCart shoppingCart = new ShoppingCart();
		BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
		try {
			ShoppingCart Cart = shoppingCartMapper.getCart(shoppingCart).get(0);
			if (Cart.getNumber() == 1) {
				shoppingCartMapper.deleteCartId(Cart.getId());
				return;
			}
			Cart.setNumber(Cart.getNumber() - 1);
			shoppingCartMapper.putCartNumber(Cart);
		} catch (Exception e) {
			throw new DeletionNotAllowedException("Error：前端未处理套餐与菜品id冲突问题！");
		}
	}
}
